//
//  NetworkAPI.swift
//  NetworkDemo
//
//  Created by xiaoyouxinqing on 5/5/20.
//  Copyright © 2020 xiaoyouxinqing. All rights reserved.
//

import Foundation
import SwiftyJSON

//NetworkAPI调用NetworkManager发出http请求
//并对请求的结果进行解析
class NetworkAPI {
    //recommendPostList和hotPostList是否可以合并成一个API？
    static func eventList(category1: FirstNavigation, category2:SecondNavigation, page: Int, completion: @escaping (Result<BaseResponse<[EventBrief]>, Error>) -> Void) {
        //通过设置parameter的方式，还没有调通
//        let parameters: [String : Any] = [
//            "category1": category1,h
//            "category2": category2,
//            "page":page
//        ]
        var path = "/event/list"
        path = "\(path)/\(category1)/\(category2)/\(page)"
        NetworkManager.shared.requestGet(path: path, parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<[EventBrief]>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
        //.cancel() 调用这个函数，如果网络请求还没有发送完成则取消
        //什么情况下外部需要用到函数返回值DataRequest————需要取消请求的时候
        //例如：搜索模块，每输入一个字就发送一个网络请求，输入下一个字就需要取消之前的网络请求
    }
        
    static func eventDetail(eventId: Int, completion: @escaping (Result<BaseResponse<EventDetail>, Error>) -> Void) {
        var path = "/event/detail"
        path = "\(path)/\(eventId)"
        NetworkManager.shared.requestGet(path: path, parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<EventDetail>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }

    static func eventCreate(context: EventTable, completion: @escaping (Result<BaseResponse<EventDetail>, Error>) -> Void) {
        //需要将object转为dict，先将对象转为Data,然后将Data转为JSON
        
        guard let data: Data = try? JSONEncoder().encode(context) else {
            return
        }
        guard let parameters = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            return
        }
        
        NetworkManager.shared.requestPost(path: "/event/create", parameters: parameters) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<EventDetail>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    
    static func eventJoin(eventId: Int, completion: @escaping (Result<BaseResponse<String>, Error>) -> Void) {
        //需要将object转为dict，先将对象转为Data,然后将Data转为JSON
        
        let parameters = ["eventId" : eventId]
        NetworkManager.shared.requestPost(path: "/event/join", parameters: parameters) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<String>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userLoginOrSignup(telephone: Int, password: String, completion: @escaping (Result<BaseResponse<UserBrief>, Error>) -> Void) {
        let parameters = ["telephone" : telephone, "password": password] as [String : Any]
        NetworkManager.shared.requestPost(path: "/user/loginOrSignup", parameters: parameters) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<UserBrief>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userUpdateInfo(userInfo: UserBrief, completion: @escaping (Result<BaseResponse<String>, Error>) -> Void) {
        let parameters = ["avatar" : userInfo.avatar,
                          "name": userInfo.name,
                          "signature": userInfo.signature,
                          "gender": userInfo.gender,
                          "birthday": userInfo.birthday,
                          "hometown": userInfo.hometown] as [String : Any]
        NetworkManager.shared.requestPost(path: "/user/updateInfo", parameters: parameters) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<String>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userFollowingList(completion: @escaping (Result<BaseResponse<[UserBrief]>, Error>) -> Void) {
        NetworkManager.shared.requestGet(path: "/user/followinglist", parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<[UserBrief]>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userFollowerList(completion: @escaping (Result<BaseResponse<[UserBrief]>, Error>) -> Void) {
        NetworkManager.shared.requestGet(path: "/user/followerlist", parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<[UserBrief]>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userInfo(completion: @escaping (Result<BaseResponse<UserForVisitor>, Error>) -> Void) {
        NetworkManager.shared.requestGet(path: "/user/info", parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<UserForVisitor>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    static func userHome(completion: @escaping (Result<BaseResponse<UserDetail>, Error>) -> Void) {
        NetworkManager.shared.requestGet(path: "/user/home", parameters: nil) { result in
            switch result {
            case let .success(data):
                let parseResult: Result<BaseResponse<UserDetail>, Error> = self.parseData(data)
                completion(parseResult)
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
    
    
    private static func parseData<T: Decodable>(_ data: Data) -> Result<T, Error> {
        let jsonString = JSON(data)
        print(jsonString)
//
//        try! JSONDecoder().decode(T.self, from: data)
        guard let decodedData =  try? JSONDecoder().decode(T.self, from: data) else {
            let error = NSError(domain: "NetworkAPIError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can not parse data"])
            return .failure(error)
        }
        return .success(decodedData)
    }
}


